package com.wxxymakers.cklabrecruit.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.wxxymakers.cklabrecruit.entity.RegisterInfo;
import com.wxxymakers.cklabrecruit.service.RegisterInfoService;
import com.wxxymakers.cklabrecruit.service.SysInfoService;
import com.wxxymakers.cklabrecruit.utils.RandomVerify;
import com.wxxymakers.cklabrecruit.utils.RestResponse;
import io.github.biezhi.excel.plus.exception.ExcelException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;

/**
 * @AUTHOR soft
 * @DATE 2018/11/5 20:46
 * @DESCRIBE 页面视图层
 */
@Controller
@Slf4j
public class ViewController {

    @Value("${upload}")
    private String uploadPath;

    private final RegisterInfoService registerInfoService;

    private final SysInfoService sysInfoService;

    @Autowired
    public ViewController(RegisterInfoService registerInfoService, SysInfoService sysInfoService) {
        this.registerInfoService = registerInfoService;
        this.sysInfoService = sysInfoService;
    }

    /*
     * 登录页面
     */
    @GetMapping("/login")
    public String login() {
        return "login";
    }

    /*
     * 关于页面
     */
    @GetMapping("/about")
    public String about() {
        return "about";
    }

    /*
     * 宣传片播放页
     */
    @GetMapping("/video")
    public String video(@RequestHeader("Referer") String referer) {
        System.out.println(referer);
        return "video";
    }

    @GetMapping("/video/f")
    public void video(HttpServletResponse response,
                      @RequestHeader(value = "Range", required = false) String range) throws IOException {
        File file = new File(uploadPath, "video.mp4");
        if (file.exists()) {
            FileInputStream in = new FileInputStream(file);
            long size  = Files.size(file.toPath());
            long start = 0;
            long end   = size - 1;

            if (range != null) {
                start = Long.parseLong(range.substring(range.indexOf("=") + 1, range.lastIndexOf("-")));
                String ends = range.substring(range.lastIndexOf("-") + 1);
                end = ends.isEmpty() ? end : Long.parseLong(ends);

                start = start < 0 ? 0 : start;
                end = end > size - 1 ? size - 1 : end;
            }
            long contentLength = end - start + 1;

            response.setContentLengthLong(contentLength);
            response.setContentType("audio/mp4");
            response.setHeader("Accept-Ranges", "bytes");
            response.setHeader("Content-Range", String.format("bytes %s-%s/%s", start, end, size));
            response.setHeader("Content-Disposition", String.format("inline; filename=%s", file.getName()));
            response.setStatus(206);
            ServletOutputStream out = response.getOutputStream();
            StreamUtils.copyRange(in, out, start, end);
            in.close();
            out.close();
        } else {
            response.setCharacterEncoding("utf-8");
            PrintWriter writer = response.getWriter();
            ObjectMapper mapper = new ObjectMapper();
            writer.print(mapper.writeValueAsString(RestResponse.fail("no file!")));
            writer.close();
        }
    }

    /*
     * 随机验证码
     */
    @RequestMapping("/verify")
    public ResponseEntity<byte[]> verify(HttpServletRequest request) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        String code = RandomVerify.create(out);
        request.setAttribute("code", code);
        request.getSession().setAttribute(RandomVerify.S_KEY, code);
        return ResponseEntity.status(200)
                .header(HttpHeaders.CONTENT_TYPE, MediaType.IMAGE_PNG_VALUE)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=v.png")
                .body(out.toByteArray());
    }

    /*
     * 报名页面
     */
    @GetMapping({"/", "/home"})
    public String home_(HttpServletRequest request) {
        request.setAttribute("canReg", sysInfoService.canReg());
        return "home";
    }

    /*
     * 管理员主页 仪表盘
     */
    @GetMapping({"/admin/home", "/admin"})
    public String home(ModelMap map) {
        long count = registerInfoService.count();
        map.put("num", count);
        map.put("canReg", sysInfoService.canReg());
        return "admin/home";
    }

    @GetMapping("/admin/list")
    public String list() {
        return "admin/list";
    }

    /*
     * 发送邮件通知页面 面向平台下所有被选用户
     */
    @GetMapping("/admin/email")
    public String email() {
        return "admin/email";
    }

    @GetMapping("/unauth")
    @ResponseBody
    public RestResponse unauth() {
        return RestResponse.fail("权限不足！");
    }

    @RequestMapping("/access")
    @ResponseBody
    public RestResponse access() {
        return RestResponse.fail(402,"No Access（禁止访问）");
    }

    @RequestMapping("/excel/export")
    public void export_(HttpServletResponse response,
                        RegisterInfo info) {
        try {
            registerInfoService.exportExcel(response, info);
        } catch (ExcelException e) {
            log.error("导出excel异常！{}", e.getMessage());
        }
    }
}
